package top.dreamix.njitkit.ui.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.work.WorkManager
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import top.dreamix.njitkit.data.yiban.AccountRepository
import top.dreamix.njitkit.data.yiban.Account

data class YibanUiState(
    val accounts: List<Account> = emptyList(),
    val isAutoSignIn: Boolean = false
)
class YibanViewModel(application: Application) : AndroidViewModel(application) {
    private val repository = AccountRepository(application)
    val uiState: StateFlow<YibanUiState> = combine(
        repository.accountsFlow
    ) { accounts ->
        YibanUiState(
            accounts = accounts.first(),
            isAutoSignIn = WorkManager
                .getInstance(application)
                .getWorkInfosForUniqueWorkFlow("/yiban/autoSignIn").first().isEmpty()
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = YibanUiState()
    )

    fun updateAccount(account: Account) {
        viewModelScope.launch {
            val accounts = repository.accountsFlow.first()
            val newAccounts = accounts.filter { it.phone != account.phone }.plus(account)
            repository.saveAccounts(newAccounts)
        }
    }

    fun deleteAccount(phone: String) {
        viewModelScope.launch {
            val accounts = repository.accountsFlow.first()
            val newAccounts = accounts.filter { it.phone != phone }
            repository.saveAccounts(newAccounts)
        }
    }
}